<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com

 * =========================================================
 */
// +---------------------------------------------------------------------+
// | NiuCloud | [ WE CAN DO IT JUST NiuCloud ]                |
// +---------------------------------------------------------------------+
// | Copy right 2019-2029 www.niucloud.com                          |
// +---------------------------------------------------------------------+
// | Author | NiuCloud <niucloud@outlook.com>                       |
// +---------------------------------------------------------------------+
// | Repository | https://github.com/niucloud/framework.git          |
// +---------------------------------------------------------------------+


namespace addon\store\event;

use addon\pointexchange\model\Exchange;
use addon\pointexchange\model\Order;
use addon\store\model\StoreMember as StoreMemberModel;
use addon\store\model\StoreGoodsSku;

/**
 * 积分兑换订单创建之后
 */
class PointExchangeOrderCreate
{
    
	// 行为扩展的执行入口必须是run
	public function handle($data)
	{
        $order_model = new Order();
        $order_info  = $order_model->getOrderInfo([['order_id', '=', $data['order_id']]], 'site_id,member_id,delivery_store_id,exchange_goods_id,num');
        $order_info  = $order_info['data'];
        if (!empty($order_info) && !empty($order_info['delivery_store_id'])) {
            //添加店铺关注记录
            $shop_member_model = new StoreMemberModel();
            $res               = $shop_member_model->addStoreMember($order_info['delivery_store_id'], $order_info['member_id']);
            if ($res["code"] < 0) {
                return $res;
            }

            $goods_info = (new Exchange())->getExchangeInfo($order_info['exchange_goods_id']);
            $goods_info = $goods_info['data'];
            if (empty($goods_info)) return $this->error([], '未获取到兑换商品信息');

            $store_goods_sku_model = new StoreGoodsSku();
            $stock_result          = $store_goods_sku_model->decStock(["store_id" => $order_info["delivery_store_id"], "sku_id" => $goods_info["sku_id"], "store_stock" => $order_info["num"]]);
            if ($stock_result["code"] < 0) {
                return $store_goods_sku_model->error([], '当前门店库存不足,请选择其他门店');
            }
            return $stock_result;
        }
	}
	
}